import React,{ Component,useContext,createRef } from 'react';
import { Graph } from '@antv/x6'
// import SchemaBuilder from 'xrenders-schema-builder-to-20';
// import Generator from 'fr-generator';
import FlowBuilder, {
  NodeContext,
  INode,
  IRegisterNode,
} from 'react-flow-builder';
import {
  Drawer,
  Popconfirm,
  Popover,
} from 'antd';
import ConfigForm from './ConfigForm';

import $ from "jquery";
import 'jquery-ui-sortable';
import './App.css'
window.jQuery = $;
window.$ = $;

require("formBuilder");

class App extends Component {
  constructor(props) {
    super(props);
    this.state={
      registerNodes:[],
      nodes:[]
    }
    this.fb=createRef(null);
    this.fr=createRef(null);
  }

  static contextType = NodeContext;

  componentDidMount() {
    // this.init();
    this.flowInit();


    let sct = document.createElement('script');
    sct.id='form-render-script';
    sct.src='https://formbuilder.online/assets/js/form-render.min.js';
    sct.onload=()=>{
         const formData = [
      {
        type: "header",
        subtype: "h1",
        label: "formBuilder in React"
      },
      {
        type: "paragraph",
        label: "This is a demonstration of formBuilder running in a React project."
      }
    ];
 
    const  fbOptions = {
      i18n: {
        locale: 'zh-CN',
        location: 'https://formbuilder.online/assets/lang/',
        extension: '.lang'
        //override: {
        //    'en-US': {...}
        //}
      },
      defaultFields: [{
        className: "form-control",
        label: "First Name",
        placeholder: "Enter your first name",
        name: "first-name",
        required: true,
        type: "text"
      }, {
        className: "form-control",
        label: "Select",
        name: "select-1454862249997",
        type: "select",
        multiple: "true",
        values: [{
          label: 'Custom Option 1',
          value: 'test-value'
        }, {
          label: 'Custom Option 2',
          value: 'test-value-2'
        }]
      }, {
        label: "Radio",
        name: "select-1454862249997",
        type: "radio-group"
      }],
      controlPosition: 'left',
      actionButtons: [{
        id: 'smile',
        className: 'btn btn-success',
        label: '😁',
        type: 'button',
        events: {
        click: function() {
          alert('😁😁😁 !SMILE! 😁😁😁');
        }
      }
      }],
      onSave: (evt, formData)=> {
        $(this.fb.current).toggle();
        $(this.fr.current).toggle();
        
        $('#form',this.fr.current).formRender({
          formData: this.formBuilder.formData
        });
      }
    };

    
    this.formBuilder =$(this.fb.current).formBuilder(fbOptions);
    };
    document.body.appendChild(sct);

 
  }

  init=() => {
    const container = document.getElementById('container');
    const graph = new Graph({
      container,
      grid: true,
    })

    const source = graph.addNode({
      x: 180,
      y: 60,
      width: 100,
      height: 40,
      attrs: {
        body: {
          stroke: '#5F95FF',
          fill: '#EFF4FF',
          strokeWidth: 1,
        },
      },
      tools: [
        {
          name: 'node-editor',
          args: {
            attrs: {
              backgroundColor: '#EFF4FF',
            },
          },
        },
      ],
    })

    const target = graph.addNode({
      x: 320,
      y: 250,
      width: 100,
      height: 40,
      attrs: {
        body: {
          stroke: '#5F95FF',
          fill: '#EFF4FF',
          strokeWidth: 1,
        },
      },
      tools: [
        {
          name: 'node-editor',
          args: {
            attrs: {
              backgroundColor: '#EFF4FF',
            },
          },
        },
      ],
    })

    graph.addEdge({
      source,
      target,
      attrs: {
        line: {
          stroke: '#A2B1C3',
          strokeWidth: 2,
        },
      },
      tools: [
        {
          name: 'edge-editor',
          args: {
            attrs: {
              backgroundColor: '#fff',
            },
          },
        },
      ],
    })

    // 2.8.0 版本之前使用方式
  // graph.on('node:dblclick', ({ node, e }) => {
  //   node.addTools({
  //     name: 'node-editor',
  //     args: {
  //       event: e,
  //     },
  //   })
  // });
  }

  // static contextType=NodeContext;
  flowInit=()=>{
        let self = this;
        const StartNodeDisplay= () => {
          
          return <div className="start-node">{'start'}</div>;
        };
        
        const EndNodeDisplay= () => {
          return <div className="end-node">{'end'}</div>;
        };
        
        const OtherNodeDisplay= () => {
          return <NodeContext.Consumer>{(context)=>{
            let s = context;
            console.log("🚀 ~ App.js:159 ~ App ~ OtherNodeDisplay ~ s:", s)
            return <div className="other-node">{'other'}</div>;
          }}</NodeContext.Consumer>;
        };
        
        const ConditionNodeDisplay= () => {
        return <NodeContext.Consumer>{(context)=>{
          let s = context;
          console.log("🚀 ~ App.js:15999 ~ App ~ OtherNodeDisplay ~ s:", s)
          return <div className="condition-node">{'condition'}</div>;
        }}</NodeContext.Consumer>;
      };
        
    
    const registerNodes= [
      {
        type: 'start',
        name: 'start node',
        displayComponent: StartNodeDisplay,
        isStart: true,
      },
      {
        type: 'end',
        name: 'end node',
        displayComponent: EndNodeDisplay,
        isEnd: true,
      },
      {
        type: 'node',
        name: '普通节点',
        displayComponent: OtherNodeDisplay,
        configComponent: ConfigForm,
      },
      {
        type: 'condition',
        name: '条件节点',
        displayComponent: ConditionNodeDisplay,
      },
      {
        type: 'branch',
        name: '分支节点',
        conditionNodeType: 'condition',
      },
    ];
    this.setState({registerNodes:registerNodes});
  }
  
  handleChange = (nodes) => {
    this.setState({nodes});

  };
  render() {
    
    console.log('****',this.context,NodeContext);
    const {nodes,registerNodes}=this.state;
    return <div className="wrap">
      <div id="container">
      {registerNodes.length>0 && <FlowBuilder
      nodes={nodes}
      onChange={this.handleChange}
      registerNodes={registerNodes}
      DrawerComponent={Drawer}
      PopoverComponent={Popover}
      PopconfirmComponent={Popconfirm}
      historyTool
        zoomTool
    />}
      </div>
      <div className="x-render"  style={{ height: '50vh' }}>
      <div className="build-wrap" ref={this.fb}></div>
      <div id="fb-rendered-form"  ref={this.fr}>
      <form action="#" id="form"></form>
      <button className="btn btn-default edit-form" onClick={()=>{
          $(this.fb.current).toggle();
          $(this.fr.current).toggle();
      }}>Edit</button>
    </div>
       {/* <Generator  />; */}
      {/* <SchemaBuilder importBtn={true} exportBtn={true} pubBtn={true} logo={{title:"表单设计",image:"test",href:'x'}} extraBtns={[{key:1,text:'test',order:1}]}/> */}
      </div>
    </div>
  }
}

export default App;